import React, { useState, useEffect, useRef, useLocation } from 'react';
import { Tabs, Modal, Table, Button, Space } from "antd";
import { useNavigate } from 'react-router-dom';
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import Json2Excel from '@/utils/Json2Excel.js'
import { getShopOrderPage, exportShopOrderList, } from '@/api/fundsManage/billList.js';
import { Decimal } from 'decimal.js';
import { getActivityTypeCode, getOrderStatus } from "@/utils/tools.js"
import moment from 'moment'

export default function ExtractApply() {
  const navigate = useNavigate();
  const SearchFormRef = useRef()
  // tab参数值
  const tabParams = [
    {
      key: '',
      label: '全部',
    },
    {
      key: '3',
      label: '待付款',
    },
    {
      key: '6',
      label: '待分享',
    },
    {
      key: '4',
      label: '待发货',
    },
    {
      key: '5',
      label: '待收货',
    },
    {
      key: '9',
      label: '交易完成',
    },
    {
      key: '0',
      label: '交易关闭',
    },
  ]
  const columns = [
    {
      title: "订单编号",
      dataIndex: "orderCode",
      key: "orderCode",
      width: 200,
    },
    {
      title: "订单类型",
      dataIndex: "activityTypeCode",
      key: "activityTypeCode",
      width: 150,
      render: (text) => {
        return getActivityTypeCode(text)
      }
    },
    {
      title: "订单实付金额(元)",
      dataIndex: "orderPayPrice",
      key: "orderPayPrice",
      width: 200,
      render: (text, record) => {
        let freightMoney = text ? Decimal(record.freight).div(Decimal(100)).toNumber().toFixed(2) : '-'
        return text ?
          <Space direction={"vertical"}>
            {'￥' + Decimal(text).div(Decimal(100)).toNumber().toFixed(2)}< span >(含运费：￥{freightMoney})</span>
          </Space >
          : '-'

      }
    },
    {
      title: "订单退款金额(元)",
      dataIndex: "orderSalesReturnPrice",
      key: "orderSalesReturnPrice",
      width: 150,
      render: (text) => {
        return text ? '￥' + Decimal(text).div(Decimal(100)).toNumber().toFixed(2) : '-'
      }
    },
    {
      title: "商家所得(元)",
      dataIndex: "practicalStorePrice",
      key: "practicalStorePrice",
      width: 150,
      render: (text) => {
        return text ? '￥' + Decimal(text).div(Decimal(100)).toNumber().toFixed(2) : '-'
      }
    },
    {
      title: "平台所得(元)",
      dataIndex: "practicalCommission",
      key: "practicalCommission",
      width: 150,
      render: (text) => {
        return text ? '￥' + Decimal(text).div(Decimal(100)).toNumber().toFixed(2) : '-'
      }
    },
    {
      title: "下单时间",
      dataIndex: "createTime",
      key: "createTime",
      width: 200,
    },
    {
      title: "订单状态",
      dataIndex: "orderState",
      key: "orderState",
      width: 150,
      render: (text) => {
        return getOrderStatus(text)
      }
    },
    {
      title: "结算状态",
      dataIndex: "commissionStatus",
      key: "commissionStatus",
      width: 150,
      render: (text) => {
        let label = ''
        switch (text) {
          case 0:
            label = "未结算"
            break;
          case 1:
            label = "已结算"
            break;
          default:
            label = "-"
        }
        return label
      }
    },
    {
      title: "操作",
      fixed: "right",
      width: 150,
      render: (text, record) => {
        return <TheButton type='link' haspermi={['fundsManage:billList:detail']} onClick={() => { { navigate('/billList/goodsDetails', { state: { id: record.shopOrderId } }) } }}>查看详情</TheButton>
      },
    },
  ]
  // 搜索
  const searchOption = [
    { field: 'orderCode', label: '订单编号', placeholder: '申请编号', type: 'Input' },
    { field: 'time', label: '下单时间', type: 'RangePicker' },
    {
      field: 'activityTypeCode',
      label: '订单类型',
      placeholder: '全部',
      type: 'Select',
      options: [
        { value: '', label: '全部' },
        { value: 0, label: '普通订单' },
        { value: 1, label: '砍价订单' },
        { value: 2, label: '拼团订单' }
      ],
    },
    {
      field: 'commissionStatus',
      label: '结算状态',
      placeholder: '全部',
      type: 'Select',
      options: [
        { value: '', label: '全部' },
        { value: 0, label: '未结算' },
        { value: 1, label: '已结算' }
      ],
    },
  ]
  const [tabValue, setTabValue] = useState('')
  const [queryForm, setQueryForm] = useState(null) //搜索值
  const [dataSource, setDataSource] = useState([]); // 表格数据
  const [pageData, setPageData] = useState({ pageNo: 1, pageSize: 10, total: 1 }) //分页参数
  const [exportLoading, setExportLoading] = useState(false); // 导出loading
  const [tableLoading, setTableLoading] = useState(false); // 表格loading
  useEffect(() => {
    getData(pageData)
  }, [])

  //获取数据
  const getData = async (value) => {
    delete value.total
    if (value && value.hasOwnProperty('time')) {
      value.createTimeStart = value.time[0].format('YYYY-MM-DD') + ' 00:00:00'
      value.createTimeEnd = value.time[1].format('YYYY-MM-DD') + ' 23:59:59'
      delete value.time
    }
    setTableLoading(true)
    await getShopOrderPage({ ...value }).then(res => {
      if (res.code === 0 && res.data) {
        setDataSource(res.data)
        setPageData({ pageNo: res.pageNo, pageSize: res.pageSize, total: res.totalCount })
      }
      setTableLoading(false)
    })

  }
  // tab值切换
  const tabChange = (e) => {
    setTabValue(e)
    getData({ pageNo: 1, pageSize: 10, orderState: e, ...queryForm })
  }
  // 分页切换
  const pageChange = async (pagination) => {
    await getData({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
      ...queryForm,
      orderState: tabValue
    })
  }
  // 搜索
  const onFormSearch = (value) => {
    getData({ ...value, pageNo: 1, pageSize: 10, orderState: tabValue }).then(res => {
      setQueryForm({ ...value })
    })
  }
  // 搜索重置
  const onReset = () => {
    setQueryForm(null)
    getData({ pageNo: 1, pageSize: 10, orderState: tabValue })
  }
  // 导出
  const exportGoods = () => {
    if (queryForm === null) {
      return Modal.warning({ title: '提醒', content: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。', });
    }
    setExportLoading(true)
    if (queryForm && queryForm.hasOwnProperty('time')) {
      queryForm.createTimeStart = queryForm.time[0].format('YYYY-MM-DD') + ' 00:00:00'
      queryForm.createTimeEnd = queryForm.time[1].format('YYYY-MM-DD') + ' 23:59:59'
      delete queryForm.time
    }
    exportShopOrderList({ ...queryForm, orderState: tabValue }).then(res => {
      if (res.code === 0) {
        let data = []
        res.data.forEach(item => {
          let { commissionStatus, orderState, activityTypeCode } = ''
          // 结算状态
          switch (item.commissionStatus) {
            case 0:
              commissionStatus = "未结算"
              break;
            case 1:
              commissionStatus = "已结算"
              break;
            default:
              commissionStatus = "-"
          }
          //订单状态
          orderState = getOrderStatus(item.orderState)
          // 订单类型
          switch (item.activityTypeCode) {
            case 0:
              activityTypeCode = "普通订单"
              break;
            case 1:
              activityTypeCode = "砍价订单"
              break;
            case 2:
              activityTypeCode = "拼团订单"
              break;
            default:
              activityTypeCode = "字段值错误"
          }
          data.push({
            ...item,
            commissionStatus,
            orderState,
            activityTypeCode,
            orderPayPrice: item.orderPayPrice ? Decimal(item.orderPayPrice).div(Decimal(100)).toNumber().toFixed(2) : '-',
            orderSalesReturnPrice: item.orderSalesReturnPrice ? Decimal(item.orderSalesReturnPrice).div(Decimal(100)).toNumber().toFixed(2) : '-',
            practicalStorePrice: item.practicalStorePrice ? Decimal(item.practicalStorePrice).div(Decimal(100)).toNumber().toFixed(2) : '-',
            practicalCommission: item.practicalCommission ? Decimal(item.practicalCommission).div(Decimal(100)).toNumber().toFixed(2) : '-'
          })
        })
        const option = {
          fileName: '对账订单列表',
          header: [
            {
              prop: "orderCode",
              title: '订单编号',
              width: 25,
            },
            {
              prop: "activityTypeCode",
              title: '订单类型',
            },
            {
              prop: "orderPayPrice",
              title: '订单实付金额(元)',
              width: 25,
            },
            {
              prop: "orderSalesReturnPrice",
              title: '订单退款金额(元)',
              width: 25,
            },
            {
              prop: "practicalStorePrice",
              title: '已结算金额(元)',
            },
            {
              prop: "practicalCommission",
              title: '商家所得(元)',
            },
            {
              prop: "createTime",
              title: '下单时间 ',
              width: 25
            },
            {
              prop: "orderState",
              title: '订单状态',
            },
            {
              prop: "commissionStatus",
              title: '结算状态',
            },
          ],
          dataSource: data
        }
        Json2Excel(option)
        setExportLoading(false)
      } else {
        message.info('导出失败请重试');
        setExportLoading(false)
      }
    })
  }
  return (
    <div className='wrap-box wrap-box-content'>
      <TheQueryForm ref={SearchFormRef} option={searchOption} show onGetValues={(values) => onFormSearch(values)}
        onReset={(values) => onReset(values)}>
        <TheButton onClick={exportGoods} haspermi={['fundsManage:billList:export']} loading={exportLoading}>导出</TheButton>
      </TheQueryForm>
      <Tabs defaultActiveKey={tabValue} items={tabParams} onChange={tabChange} />
      <Table
        loading={tableLoading}
        scroll={{ x: 960 }}
        bordered
        columns={columns}
        dataSource={dataSource}
        rowKey={'orderCode'}
        onChange={pageChange}
        pagination={{ position: ['bottomCenter'], current: pageData.pageNo, pageSize: pageData.pageSize, total: pageData.total, showSizeChanger: false }}
      />
    </div>
  )
}